package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        //判断本次请求是否需要处理
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/upload.html",
                "/user/**"
        };
        for (String url : urls) {//循环判断是否满足放行要求
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {//如果返回值为true,代表请求url和放行的一样
                //放行请求
                System.out.println("此请求被放行");
                filterChain.doFilter(request, response);
                return;
            }
        }
        //判断登录状态,如果已经登录,则直接放行
        System.out.println("此请求被拦截");
        //获得用户登录信息
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        Long userId = (Long) session.getAttribute("userId");
        if (employee == null && userId==null) {
            //未登录状态,返回为登录结果,跳转登录界面
            String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
            System.out.println(jsonString);
            response.getOutputStream().write(jsonString.getBytes());
            return;
        }

        //登录成功后绑定用户id
        if (employee!=null){
            BaseContext.threadLocal.set(employee);
        }else if (userId!=null){
            BaseContext.threadLocal.set(userId);
        }
        filterChain.doFilter(request, response);
        return;
    }
}
